<template>
  <div class="mod-user">
    <div>
      <el-drawer title="课程详情" :visible.sync="addOrUpdateVisible" :with-header="false" size="650px">
        <div class="right-container">
          <div class="container-header">
            <div style="font-size: 14px">发票信息</div>
            <div @click="handleClose">
              <i class="el-icon-close" style="font-size: 18px"></i>
            </div>
          </div>
          <div class="container-content background-color-grey padding-10">
            <div class="bg-white border-radius">
              <div class="flex justify-between align-center margin-bottom-sm padding-lg border-bottom card-heard-title ">
                <div>
                  <i class="el-icon-collection-tag" style="font-size: 18px"></i>
                  发票信息
                </div>
              </div>
              <div>
                <el-form :model="classOrder" ref="orderInvoicePay" label-width="100px" >
                  <el-form-item style="margin-bottom: 0;" label="购买方名称:">
                    {{classOrder.userName}}
                  </el-form-item>
                  <el-form-item  style="margin-bottom: 0;" label="纳税识别号:">
                    {{classOrder.buyType==1?classOrder.idCard:classOrder.creditCode}}
                  </el-form-item>
                  <el-form-item style="margin-bottom: 0;" label="开票类型:">
                    {{transformType(classOrder.type)}}
                  </el-form-item>
                  <el-form-item  style="margin-bottom: 0;" label="开票金额:">
                    {{classOrder.orderAmount}}
                  </el-form-item>
                  <el-form-item style="margin-bottom: 0;" label="电子邮箱:">
                    {{classOrder.email}}
                  </el-form-item>
                  <el-form-item style="margin-bottom: 0;" label="发票类型:" prop="status">
                    <el-radio-group v-model="classOrder.status">
                      <el-radio :label="0">未开票</el-radio>
                      <el-radio :label="1">已开票</el-radio>
                      <el-radio :label="3">发票作废</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <template v-if="classOrder.status==1">
                      <el-form-item style="margin-bottom: 5px;" label="发票编号:" prop="buyName" >
                        <el-input v-model="classOrder.invoiceNumber"></el-input>
                      </el-form-item>
                      <el-form-item style="padding-bottom: 10px;"  label="下载链接:" prop="creditCode" >
                        <div class="flex justify-between">
                          <el-input v-model="classOrder.invoiceLink"></el-input>
                          <OssUploadImagButton :limit="1" :fileType="['image/*']" :fileSize="5120" :isShowUploadImg="true"
                                               ref="imgUploadRef" @input="uploadImg" :isShowBtn="true"></OssUploadImagButton>
                        </div>

                      </el-form-item>
                  </template>
                </el-form>
              </div>
            </div>
            <div class="div-jiange"></div>
            <div class="bg-white border-radius">
              <div class="flex justify-between align-center margin-bottom-sm padding-lg border-bottom card-heard-title ">
                <div>
                  <i class="el-icon-collection-tag" style="font-size: 18px"></i>
                  支付信息
                </div>
              </div>
              <div class="padding-md flex " >
                <div class="flex-1">订单编号：{{classOrder.channelOrderNo}}</div>
              </div>
              <div class="padding-md flex ">
                <div class="flex-1">订单状态：{{transformPaymentStatus(classOrder.paymentStatus)}}</div>
              </div>
              <div class="padding-md flex ">
                <div class="flex-1">支付时间：{{classOrder.paymentTime}}</div>
              </div>
              <div class="padding-md flex ">
                <div class="flex-1">支付方式：{{transformPay(classOrder.paymentType)}}</div>
              </div>
            </div>
            <div class="div-jiange"></div>
            <div  class="bg-white border-radius margin-top-md">
              <div class="flex justify-between align-center margin-bottom-sm padding-lg border-bottom card-heard-title">
                <div>
                  <i class="el-icon-collection-tag" style="font-size: 18px"></i>
                  商品明细
                </div>
              </div>
              <div class="padding-lr-lg padding-bottom-lg" >

                <el-table :header-cell-style="tableHeaderStyle" :data="classOrder.classOrderItemList"  border
                          v-loading="false"  style="width: 100%;">
                  <el-table-column prop="id" label="序号" width="60" align="center">
                    <template slot-scope="scope">
                      <span>{{scope.row.xuhao}}</span>
                    </template>
                  </el-table-column>

                  <el-table-column prop="manageName" header-align="left" align="left" label="产品">
                  </el-table-column>

                  <el-table-column prop="price" header-align="center" align="center" label="单价" width="100">
                  </el-table-column>

                  <el-table-column prop="number" header-align="center" align="center" label="数量" width="100">
                    <!--                    <template slot-scope="scope">-->
                    <!--                      <span v-if="scope.row.score&&scope.row.score<=0">未考试</span>-->
                    <!--                      <span v-else-if="scope.row.status === 1" >已通过&nbsp;&nbsp;考试得分：{{scope.row.score}} / 100</span>-->
                    <!--                      <span v-else>未通过&nbsp;&nbsp;考试得分：{{scope.row.score}} / 100</span>-->
                    <!--                    </template>-->
                  </el-table-column>
                </el-table>
                <!--                <el-pagination @size-change="sizeChangeHandleExam" @current-change="currentChangeHandleExam"-->
                <!--                               :current-page="pageIndexExam" :page-sizes="[10, 20, 50, 100]" :page-size="pageSizeExam" :total="totalPageExam"-->
                <!--                               layout="total, sizes, prev, pager, next, jumper">-->
                <!--                </el-pagination>-->
              </div>
            </div>
          </div>
          <div class="flex justify-center padding-10">
            <el-button @click="addOrUpdateVisible = false">取消</el-button>
            <el-button type="primary" @click="dataFormSubmit">保存</el-button>
          </div>
        </div>
      </el-drawer>
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">

      <el-form-item label="订单编号:">
        <el-input class="selectWidth" v-model="dataForm.channelOrderNo" placeholder="" clearable></el-input>
      </el-form-item>
      <el-form-item label="发票抬头:">
        <el-input class="selectWidth" v-model="dataForm.buyName" placeholder="" clearable></el-input>
      </el-form-item>

      <el-form-item label="发票类型:">
        <el-select class="selectWidth"  v-model="dataForm.invoiceType" placeholder="" >
          <el-option
            v-for="item in options2"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式:">
        <el-select class="selectWidth" v-model="dataForm.paymentType" placeholder="">
          <el-option
            v-for="item in optionsFangshi"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item  label="发票状态:">
        <el-select class="selectWidth"  v-model="dataForm.status" placeholder="" >
          <el-option
            v-for="item in options1"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态:">
        <el-select class="selectWidth"  v-model="dataForm.paymentStatus" placeholder="" >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item  prop="invoiceApplicationTimeYear"  label="申请年度:">
        <el-date-picker
          v-model="dataForm.invoiceApplicationTimeYear"
          type="year"
          value-format="yyyy"
          placeholder="">
        </el-date-picker>
      </el-form-item>

      <el-form-item  label="申请时间">
        <el-date-picker
          v-model="orderDate"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>



      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button @click="exportDataList()">导出</el-button>
        <el-dropdown @command="handleCommand" style="margin-left: 10px;">
          <el-button type="primary">
            批量开票<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="plwkp">设为未开票</el-dropdown-item>
            <el-dropdown-item command="plykp">设为已开票</el-dropdown-item>
            <el-dropdown-item command="plzf">设为已作废</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-form-item>
    </el-form>
    <el-table
      ref="orderListTableRef"
      :data="dataList" :height="height"
      border
      :summary-method="getSummaries"
      show-summary
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        prop="paymentTime"
        header-align="center"
        align="center"
        label="支付时间">
      </el-table-column>
      <el-table-column
        prop="channelOrderNo"
        header-align="center"
        align="center"
        label="订单编号">
      </el-table-column>
      <el-table-column
        prop="userName"
        header-align="center"
        align="center"
        label="客户姓名">
      </el-table-column>
      <el-table-column
        prop="creditCode"
        header-align="center"
        align="center"
        label="开票业务流水号">
        <template slot-scope="scope">
          <span>{{transformLiu(scope.row)}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="orderAmount"
        header-align="center"
        align="center"
        label="发票金额">
      </el-table-column>
      <el-table-column
        prop="name"
        header-align="center"
        align="center"
        label="发票类型">
        <template slot-scope="scope">
          <span>{{transformType(scope.row.type)}}</span>
        </template>
      </el-table-column>
      <el-table-column

        header-align="center"
        align="center"
        label="支付方式">
        <template slot-scope="scope">
          <span>{{transformPay(scope.row.paymentType)}}</span>
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        label="订单状态">
        <template slot-scope="scope">
          <el-button v-if="scope.row.paymentStatus==4" type="text" size="small" @click="openUrlHong(scope.row)">{{transformPaymentStatus(scope.row.paymentStatus)}}</el-button>

          <span v-else> {{transformPaymentStatus(scope.row.paymentStatus)}}</span>

        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        label="开票状态">
        <template slot-scope="scope">
          <span>{{transformStatus(scope.row.status)}}</span>
        </template>

      </el-table-column>
      <el-table-column
        prop="fphm"
        header-align="center"
        align="center"
        width="170"
        label="发票号">
        <template slot-scope="scope">
          <el-button  type="text" size="small" @click="openUrl(scope.row)">{{transformFa(scope.row)}}</el-button>
        </template>
      </el-table-column>

      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button  type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100,999]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
  </div>

</div>
</template>

<script>
  import OssUploadImagButton from '../oss/oss-upload-img-button.vue'
  import { saveAs } from 'file-saver';

  export default {
    data () {
      return {
        height: 0,
        orderDate:'',
        tableHeaderStyle: { background: '#f5f7fa !important', height: '20px !important', padding: '4px !important' },
        dataForm: {
          year: '',
          invoiceApplicationTimeYear:'',
          channelOrderNo: '',
          userName: '',
          userPhone: '',
          paymentType: '',
          creditCode:'',
          invoiceType:'',
          status:'',
          paymentStatus:''
        },
        url: '',
        fileList: [],
        optionsFangshi: [
          {
          value: '',
          label: '请选择'
        },{
          value: '0',
          label: '微信'
        }, {
          value: '1',
          label: '支付宝'
        }, {
          value: '3',
          label: '线下转账'
        }],
        options2: [
          {
            value: '',
            label: '请选择'
          },
          {
          value: '1',
          label: '普票'
        }, {
          value: '2',
          label: '专票'
        }],
        options1: [
          {
            value: '',
            label: '请选择'
          },
          {
          value: '0',
          label: '未开'
        }, {
          value: '1',
          label: '已开'
        },
        {
          value: '3',
          label: '发票作废'
        },
          {
            value: '5',
            label: '申请换开'
          }],
        options: [
          {
            value: '',
            label: '请选择'
          },
          {
          value: '2',
          label: '已支付'
          }, {
          value: '0',
          label: '支付中'
        }, {
            value: '4',
            label: '已退款'
          }
        ],
        classOrder: {
          name: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false
      }
    },
    components: {
      OssUploadImagButton
    },
    activated () {
      this.url = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`)
      this.getDataList()
    },
    mounted() {
      console.log(document.body.clientHeight)
      // 至于减去多少，这个要看你的页面高度和你想将滚动轴固定在哪里了，数值可以更换
      this.$nextTick(() => {
        let tableHeight = document.body.clientHeight - 345
        this.height = tableHeight
      })
    },
    methods: {

      getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index == 0) {
            sums[index] = '合计';
            return;
          }
          if (column.property == 'orderAmount') {
            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0).toFixed(2); // 保留两位小数
              sums[index] += ' 元'; // 加上单位
            } else {
              sums[index] = 'N/A';
            }
          } else {
            sums[index] = '';
          }
        });
        return sums;
      },
      uploadImg(data) {
        console.log("上传后的数据", data)
        this.classOrder.invoiceLink = data.url
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handleClose() {
        this.addOrUpdateVisible = false; // 关闭外层 Drawer 时不关闭内层 Drawer
      },
      transformStatus(type){
        if(type==0||type==4){
          return "未开票";
        }else if(type==1||type==5){
          return "已开票";
        }else if(type==2){
          return "无需开票";
        }else if(type==3){
          return "已作废";
        }
      },
      transformType(type){
        if(type==1){
          return "普票";
        }else if(type==2){
          return "专票";
        }else {
          return "无需开票";
        }
      },
      transformLiu(order){
        if(order.lanNewOrderCode){
          return order.lanNewOrderCode;
        }else if(order.hongOrderCode){
          return order.hongOrderCode;
        }else {
          return order.lanOrderCode;
        }
      },
      transformFa(order){
        if(order.lanNewOrderCode){
          return order.fphm2;
        }else if(order.hongOrderCode){
          return order.hzfphm;
        }else {
          return order.fphm;
        }
      },
      transformUrl(order){
        if(order.lanNewOrderCode){
          return order.lanh5url2;
        }else if(order.hongOrderCode){
          return order.hongh5url;
        }else {
          return order.lanh5url;
        }
      },
      openUrlHong(order) {
        if(order.hongh5url){
          window.open(order.hongh5url)
        }else{
          alert("暂无红票")
        }
      },
      openUrl(order) {
        if(order.lanNewOrderCode){
          window.open(order.lanh5url2)
        }else if(order.hongOrderCode){
          window.open(order.hongh5url)
        }else {
          window.open(order.lanh5url)
        }
      },
      transformPay(paymentType){
        if (paymentType == 1) {
          return "支付宝";
        } else if (paymentType == 3) {
          return "线下转账";
        } else {
          return "微信";
        }
      },
      transformPaymentStatus(paymentStatus){
        //支付状态 0未支付 1支付中 2 已支付 3,退款中 4,已退款
        if (paymentStatus == 0) {
          return "未支付";
        } else if (paymentStatus == 1) {
          return "支付中";
        } else if (paymentStatus == 2) {
          return "已支付";
        } else if (paymentStatus == 3) {
          return "退款中";
        } else if (paymentStatus == 4) {
          return "已退款";
        }
      },
      exportDataList() {
        let searchParams = {
          ...this.dataForm,
          flag:"invoice",
          page: this.pageIndex,
          limit: this.pageSize,
          startDate: this.orderDate && this.orderDate.length > 0 ? this.orderDate[0] + " 00:00:00" : "",
          endDate: this.orderDate && this.orderDate.length > 0 ? this.orderDate[1] + " 23:59:59" : "",
        }
        if( this.dataListSelections.length != 0){
          const ids =  this.dataListSelections.map(item => item.id).join(',');
          searchParams.ids = ids;
        }
        this.$http.exportFile('/class/order/exportInvoiceList', searchParams)
          .then(async (res) => {
            console.log(res);
            let blob = new Blob([res])
            saveAs(blob, "发票管理.xlsx")
          }).catch(error => {
          console.error('文件导出失败:', error)
        })
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true

        var params={
          ...this.dataForm,
          flag:"invoice",
          page: this.pageIndex,
          limit: this.pageSize,
          startDate: this.orderDate&&this.orderDate.length>0?this.orderDate[0]+ " 00:00:00":"",
          endDate: this.orderDate&&this.orderDate.length>0?this.orderDate[1]+ " 23:59:59":"",
        }

        this.$http({
          url: this.$http.adornUrl('/class/order/list'),
          method: 'get',
          params: this.$http.adornParams(params)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
          this.$nextTick(() => {
            this.$refs.orderListTableRef.doLayout(); // 修复表格布局
          });

          this.repairTableByRef('orderListTableRef')
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        console.log(val)
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$http({
          url: this.$http.adornUrl(`/class/order/info/${id}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("获取订单详情", data)
            let res = data.classOrder;
            this.classOrder=res;
            //处理发票号码
            this.classOrder.invoiceNumber = this.transformFa(this.classOrder);
            this.classOrder.invoiceLink = this.transformUrl(this.classOrder);
            if (this.classOrder.classOrderItemList && this.classOrder.classOrderItemList.length > 0) {
              this.classOrder.classOrderItemList.forEach((item1, index1) => {
                //设置子的序号
                item1.xuhao = index1+1;
              })
            }
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      dataFormSubmit() {
        // let addParams = Object.assign({}, this.dataForm)
        // console.log(addParams)

            this.$http({
              url: this.$http.adornUrl(`/class/order/update`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.classOrder.id,
                'type': this.classOrder.type,
                'invoiceNumber': this.classOrder.invoiceNumber,
                'invoiceLink': this.classOrder.invoiceLink

              })
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.addOrUpdateVisible = false
                    this.getDataList()
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })


      },  // 更多操作
      handleCommand (command) {
        if( this.dataListSelections.length === 0){
          this.$message({
            message: '请选择要操作的数据',
            type: 'warning',
            duration: 1500
          })
          return
        }
        const ids =  this.dataListSelections.map(item => item.id)
        if(command=='plwkp'){
          this.$confirm(`确定设为未开票吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$http({
              url: this.$http.adornUrl('/class/order/bachUpdateStatus'),
              method: 'post',
              data: this.$http.adornData({
                'ids':ids,
                'status':0
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.getDataList()
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          })
        }else if(command=='plzf'){
          this.$confirm(`确定设为已作废吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$http({
              url: this.$http.adornUrl('/class/order/bachUpdateStatus'),
              method: 'post',
              data: this.$http.adornData({
                'ids':ids,
                'status':3
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.getDataList()
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          })
        }else if(command=='plykp'){
          this.$confirm(`确定设为已开票吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$http({
              url: this.$http.adornUrl('/class/order/bachUpdateStatus'),
              method: 'post',
              data: this.$http.adornData({
                'ids':ids,
                'status':1
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.getDataList()
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          })
        }
      },
      // 删除
      deleteHandle (id) {
        var userIds = id ? [id] : this.dataListSelections.map(item => {
          return item.userId
        })
        this.$confirm(`确定进行删除操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/class/study/delete'),
            method: 'post',
            data: this.$http.adornData(userIds, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }).catch(() => {})
      }
    }
  }
</script>
<style>
.right-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.container-header {
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px
}
</style>
